<template>
  <el-dialog width="90%" :visible="inventoryDialogVisible" @close="close">
    <div class="prompt">
      <span>盘点人员</span>
    </div>
    <div class="radio">
      <el-radio-group v-model="inventoryRange">
        <el-radio label="人员维度" />
        <el-radio label="部门维度" />
      </el-radio-group>
    </div>
    <div v-show="inventoryRange === '部门维度'" class="department">
      <el-tree :data="departmentTree" show-checkbox node-key="value" :expand-on-click-node="false" />
    </div>
    <div v-show="inventoryRange === '人员维度'" class="people">
      <el-form v-model="formData" label-width="100px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="研发部">
              <el-select v-model="formData.workType" placeholder="请选择" @change="updateDepartmentList">
                <el-option v-for="item in formOption.workType" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="部门">
              <el-select v-model="formData.department" placeholder="请选择">
                <el-option v-for="item in filteredDepartmentList" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-button type="primary" @click="setParamAndGetPeopleList()">查询</el-button>
            <el-button @click="resetDialog">重置</el-button>
          </el-col>
        </el-row>
      </el-form>
      <el-transfer ref="transfer" v-model="transferValue" filterable filter-placeholder="请输入姓名或认证号" :data="peopleDetailList" :titles="['未选择','已选择']" @change="handleTransferChange" />
    </div>
    <template #footer>
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" @click="start">盘点</el-button>
    </template>
  </el-dialog>
</template>

<script>

import { getDeptInfoDetail, getPeopleList, start } from '@/api/department'

export default {
  props: {
    inventoryDialogVisible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      inventoryRange: '人员维度',
      formData: {
        workType: '',
        department: [],
        user: ''
      },
      formOption: {
        workType: [],
        department: [],
        user: []
      },
      departmentTree: [],
      peopleDetailList: [],
      transferValue: [],
      selectedIds: [], // 初始化为空数组
      param: {
        workType: '',
        department: ''
      },
      filteredDepartmentList: [] // 初始化filteredDepartmentList为空数组
    }
  },
  watch: {
    inventoryDialogVisible(newVal) {
      if (newVal) {
        this.getOptions() // 当 inventoryDialogVisible 变为 true 时调用 getOptions
      }
    }
  },
  mounted() {
    // 如果 dialog 组件在挂载时就是可见的，您可能还需要在这里调用 getOptions
    if (this.inventoryDialogVisible) {
      this.getOptions() // 获取选项并设置默认的研发部
      this.updateDepartmentList() // 设置默认的部门
    }
  },
  methods: {
    getOptions() {
      getDeptInfoDetail().then(res => {
        // 重置workType和department列表
        this.formOption.workType = []
        this.formOption.department = []
        // 遍历data数组，找到研发部的所有name并添加到workType中
        // 同时构建department列表
        res.data.forEach(item => {
          // 假设研发部的name是“研发部”
          this.formOption.workType.push(item)
          // 遍历children数组，将deptName添加到department列表中
          if (item.children && Array.isArray(item.children)) {
            item.children.forEach(child => {
              this.formOption.department.push({
                id: child.id,
                name: child.name,
                parentId: item.id // 设置parentId为研发部的id
              })
            })
          }
        })

        this.updateDepartmentList()
        console.log('this.formOption', this.formOption)
        console.log('this.worType', this.formOption.workType)
        console.log('this.department', this.formOption.department)
      }).catch(error => {
        console.error('获取部门信息时出错:', error)
      })
      console.log('this.formOption', this.formOption)
    },
    resetDialog() {
      // 重置dialog中的数据
      this.inventoryRange = '人员维度'
      this.formData = {
        workType: '',
        department: '',
        user: ''
      }
      this.param = {
        workType: '',
        departmentId: ''
      }

      // 清空右侧的列表
      this.filteredDepartmentList = []
      this.peopleDetailList = []
      this.transferValue = []
      this.selectedIds = [] // 清空已选择的ID列表
      // ... 重置其他相关数据 ...
    },

    close() {
      this.resetDialog()
      this.inventoryDialogVisible = false
      this.$emit('update:inventoryDialogVisible', false)
    },
    updateDepartmentList() {
      // 根据选择的研发部名称来过滤部门列表
      const selectedWorkTypeId = this.formData.workType
      this.filteredDepartmentList = this.formOption.department.filter(dept => {
        // 假设研发部名称存储在dept的某个属性中，这里假设是dept.parentName
        return dept.parentId === selectedWorkTypeId
      })

      // 如果filteredDepartmentList不为空，则设置第一个部门为默认部门
      if (this.filteredDepartmentList.length > 0) {
        this.formData.department = this.filteredDepartmentList[0].id
      } else {
        this.formData.department = '' // 如果没有匹配的部门，则清空部门选择
      }
    },
    setParamAndGetPeopleList() {
      // 收集研发部和部门的ID
      this.param.workTypeId = this.formData.workType
      this.param.departmentId = this.formData.department

      // 调用getPeopleList方法
      this.getPeopleList()
    },
    getPeopleList() {
      // 获取人员列表

      getPeopleList(this.param).then(res => {
        // 假设res.data是一个包含人员的数组
        // 转换为<el-transfer>所需的结构，通常包含key和label属性
        this.peopleDetailList = res.data.map(item => ({
          key: item.id, // 假设每个对象都有一个唯一的id作为key
          label: item.name // 假设name是你要在<el-transfer>中显示的文本
        }))
        // 在这里打印，以确保数组已经被填充
        console.log('this.peopleDetailList', this.peopleDetailList)
      }).catch(error => {
        console.error('获取人员列表时出错:', error)
      })
      console.log('this.peopleDetailList', this.peopleDetailList)
    },
    handleTransferChange(value, direction, movedKeys) {
      if (direction === 'right') {
        // 当项移动到右侧时，添加它们的ID到selectedIds数组
        this.selectedIds = this.selectedIds.concat(movedKeys)
      } else if (direction === 'left') {
        // 当项移动到左侧时，从selectedIds数组中移除它们的ID
        this.selectedIds = this.selectedIds.filter(id => !movedKeys.includes(id))
      }
    },
    start() {
      const param = {
        userId: this.selectedIds
      }
      console.log('this.param  ', param)
      start(param).then(response => {
        this.close()
      }).catch(error => {
        console.error('盘点出错:', error)
      })
    }
  }
}
</script>

<style>

</style>
